package com.xukang.batch.processor;

import com.xukang.batch.po.Users;
import com.xukang.batch.service.UserService;
import org.springframework.batch.item.ItemReader;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;


/**
 * 从作业参数或数据库获取执行参数，一次执行，反复拉取，直到处理完所有数据
 */
public class MyItemReader2 implements ItemReader<Users> {

    private ThreadLocal<Boolean> threadLocalContinue = ThreadLocal.withInitial(() -> true);

    private Iterator<Users> dataIterator;
    @Resource
    private UserService userService;

    @Override
    public Users read() throws Exception {
        System.out.println("read");
        if (threadLocalContinue.get()) {
            if (dataIterator == null || !dataIterator.hasNext()) {
                // 没有数据了，就再拉取
                fetchData();
            }
            return dataIterator.hasNext() ? dataIterator.next() : null;
        }
        return null;
    }

    private void fetchData() {
        List<Users> data = userService.findAll();
        if (data == null || data.size() == 0) {
            threadLocalContinue.set(false);
        }
        this.dataIterator = data.iterator();
    }


}
